import { useState, useEffect } from 'react';
import { Card, Row, Col, Modal, Descriptions, Table, message, Input, Button, Pagination } from 'antd';
import { SearchOutlined, SyncOutlined } from '@ant-design/icons';
import axios from 'axios';

// 定义数据接口
interface ShelfData {
  id: number;
  name: string;
  code: string;
  boxCount: number;
  skuTypeCount: number;
  skuTotalCount: number;
  remark?: string;
}

interface ShelfSku {
  id: string;
  boxId: string;
  skuType: string;
  skuCount: number;
  skuCode: string;
  productName: string;
}

const ShelvesOverview: React.FC = () => {
  const [shelves, setShelves] = useState<ShelfData[]>([]);
  const [loading, setLoading] = useState(false);
  const [detailVisible, setDetailVisible] = useState(false);
  const [currentShelf, setCurrentShelf] = useState<ShelfData | null>(null);
  const [skuList, setSkuList] = useState<ShelfSku[]>([]);
  const [searchCode, setSearchCode] = useState('');
  const [searchName, setSearchName] = useState('');
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(12);
  const [total, setTotal] = useState(0);

  // 获取所有货架数据
  const fetchAllShelves = async (codeParam: string = searchCode, nameParam: string = searchName, page: number = currentPage, size: number = pageSize) => {
    setLoading(true);
    try {
      const response = await axios.get('/api/Shelves/QueryShelves', {
        params: { 
          code: codeParam,
          name: nameParam,
          pageIndex: page,
          pageSize: size
        }
      });
      
      if (response.data) {
        const shelvesData = Array.isArray(response.data.data) ? response.data.data : [];
        setShelves(shelvesData);
        
        // 设置总数据量
        if (response.data.totalCount !== undefined) {
          setTotal(response.data.totalCount);
        } else {
          // 如果API没有返回总数，则使用当前数据长度作为总数（不推荐）
          setTotal(shelvesData.length);
        }
      }
    } catch (error) {
      console.error('获取货架数据失败:', error);
      message.error('获取货架数据失败');
    } finally {
      setLoading(false);
    }
  };

  // 获取货架详情
  const fetchShelfDetail = async (shelfId: number) => {
    try {
      const response = await axios.get(`/api/Shelves/GetShelvesById?id=${shelfId}`);
      
      if (response.data && response.data.code === 200) {
        setCurrentShelf(response.data.data);
        // 如果API返回了SKU列表，可以在这里设置
        setSkuList([]);
      } else {
        message.error(response.data.message || '获取货架详情失败');
      }
    } catch (error) {
      console.error('获取货架详情失败:', error);
      message.error('获取货架详情失败');
      setSkuList([]);
    }
  };

  // 初始加载数据
  useEffect(() => {
    fetchAllShelves();
  }, []);

  // 处理货架卡片点击
  const handleCardClick = (shelf: ShelfData) => {
    setCurrentShelf(shelf);
    fetchShelfDetail(shelf.id);
    setDetailVisible(true);
  };

  // 处理搜索
  const handleSearch = () => {
    setCurrentPage(1); // 搜索时重置到第一页
    fetchAllShelves(searchCode, searchName, 1, pageSize);
  };

  // 处理重置
  const handleReset = () => {
    // 先重置搜索条件
    setSearchCode('');
    setSearchName('');
    setCurrentPage(1); // 重置到第一页
    
    // 立即调用方法刷新页面，使用空字符串作为搜索条件
    fetchAllShelves('', '', 1, pageSize);
    
    message.success('已重置并刷新数据');
  };

  // 处理刷新
  const handleRefresh = () => {
    fetchAllShelves();
  };

  // 处理页码变化
  const handlePageChange = (page: number, size?: number) => {
    setCurrentPage(page);
    if (size && size !== pageSize) {
      setPageSize(size);
    }
    fetchAllShelves(searchCode, searchName, page, size || pageSize);
  };

  // 表格列定义
  const columns = [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      render: (_: unknown, __: unknown, index: number) => index + 1,
      width: 80,
    },
    {
      title: '箱号',
      dataIndex: 'boxId',
      key: 'boxId',
    },
    {
      title: 'SKU种类',
      dataIndex: 'skuType',
      key: 'skuType',
    },
    {
      title: 'SKU数量',
      dataIndex: 'skuCount',
      key: 'skuCount',
    },
    {
      title: '产品SKU',
      dataIndex: 'skuCode',
      key: 'skuCode',
    },
    {
      title: '产品名称',
      dataIndex: 'productName',
      key: 'productName',
    },
    {
      title: 'SKU数量',
      dataIndex: 'skuCount',
      key: 'skuCount2',
    },
  ];

  // 获取卡片类名
  const getCardClassName = (shelf: ShelfData) => {
    let className = 'shelf-card';
    
    // 根据SKU数量添加特殊样式，但不再添加active类
    if (shelf.skuTotalCount > 100) {
      className += ' special';
    }
    return className;
  };

  return (
    <div style={{ padding: '24px' }}>
      <div style={{ marginBottom: '24px' }}>
        <Row gutter={16}>
          <Col span={6}>
            <Input
              placeholder="输入货架编号"
              value={searchCode}
              onChange={(e) => setSearchCode(e.target.value)}
              prefix={<SearchOutlined />}
            />
          </Col>
          <Col span={6}>
            <Input
              placeholder="输入仓库名称"
              value={searchName}
              onChange={(e) => setSearchName(e.target.value)}
              prefix={<SearchOutlined />}
            />
          </Col>
          <Col span={12}>
            <Button type="primary" onClick={handleSearch} style={{ marginRight: '8px' }}>
              搜索
            </Button>
            <Button onClick={handleReset} style={{ marginRight: '8px' }}>
              重置
            </Button>
            <Button icon={<SyncOutlined />} onClick={handleRefresh}>
              刷新
            </Button>
          </Col>
        </Row>
      </div>

      <Row gutter={16}>
        {shelves.map(shelf => (
          <Col xs={24} sm={12} md={8} lg={6} xl={4} key={shelf.id}>
            <Card 
              title={shelf.code}
              onClick={() => handleCardClick(shelf)}
              loading={loading}
              className={getCardClassName(shelf)}
              hoverable={true}
            >
              <p>仓库名称: {shelf.name}</p>
              <p>箱子数: {shelf.boxCount}</p>
              <p>SKU种类: {shelf.skuTypeCount}</p>
              <p>SKU数量: {shelf.skuTotalCount}</p>
            </Card>
          </Col>
        ))}
      </Row>

      {/* 分页器 */}
      <div style={{ marginTop: '24px', textAlign: 'right' }}>
        <Pagination
          current={currentPage}
          pageSize={pageSize}
          total={total}
          showSizeChanger
          showQuickJumper
          showTotal={(total) => `共 ${total} 条`}
          pageSizeOptions={['12', '24', '36', '48']}
          onChange={handlePageChange}
          onShowSizeChange={handlePageChange}
        />
      </div>

      {/* 货架详情弹窗 */}
      <Modal
        title="货架明细"
        open={detailVisible}
        onCancel={() => setDetailVisible(false)}
        width={1000}
        footer={null}
      >
        {currentShelf && (
          <Descriptions style={{ marginBottom: 20 }}>
            <Descriptions.Item label="仓库名称">{currentShelf.name}</Descriptions.Item>
            <Descriptions.Item label="货架编号">{currentShelf.code}</Descriptions.Item>
            <Descriptions.Item label="箱子数">{currentShelf.boxCount}</Descriptions.Item>
            <Descriptions.Item label="SKU种类">{currentShelf.skuTypeCount}</Descriptions.Item>
            <Descriptions.Item label="SKU数量">{currentShelf.skuTotalCount}</Descriptions.Item>
            <Descriptions.Item label="备注">{currentShelf.remark}</Descriptions.Item>
          </Descriptions>
        )}
        
        <Table
          rowKey="id"
          columns={columns}
          dataSource={skuList}
          loading={loading}
          pagination={false}
          locale={{ emptyText: '无数据' }}
        />
      </Modal>
    </div>
  );
};

export default ShelvesOverview; 